import 'package:get/get.dart';
import '../../../common/services/user_service.dart';
import '../../../common/services/alipay_service.dart';
import '../../../common/api/points_api.dart';
import '../../../common/models/index.dart';
import '../../../common/utils/toast_util.dart';
import 'dart:developer' as developer;

class FundsController extends GetxController {
  FundsController();

  // 获取UserService实例
  final UserService userService = UserService.to;

  // 数据状态
  final RxList<PointsPackage> pointsPackages = <PointsPackage>[].obs;
  final RxList<PointsHistoryRecord> pointsHistory = <PointsHistoryRecord>[].obs;
  final RxBool isLoadingPackages = false.obs;
  final RxBool isLoadingUserPoints = false.obs;
  final RxBool isLoadingPointsHistory = false.obs;
  final RxInt selectedPackageIndex = (-1).obs;
  
  // 为了兼容GetBuilder，也提供普通属性
  List<PointsPackage> get packagesData => pointsPackages;
  List<PointsHistoryRecord> get historyData => pointsHistory;
  bool get isLoading => isLoadingPackages.value;
  bool get isLoadingRecords => isLoadingPointsHistory.value;
  int get selectedIndex => selectedPackageIndex.value;

  // 用户积分相关getter
  int get userPoints => userService.currentUser?.userPoints ?? 0;
  int get userLevel => userService.currentUser?.userLevel ?? 0;
  String get userName => userService.currentUser?.username ?? '未知用户';
  bool get isLoggedIn => userService.isLoggedIn;

  // 计算用户等级相关信息
  Map<String, dynamic> get levelInfo {
    final points = userPoints;
    
    // 简单的等级计算规则（可以根据实际需要调整）
    final levelThresholds = [0, 100, 500, 1500, 3000, 6000]; // Lv0到Lv5所需积分
    
    int currentLevel = 0;
    for (int i = levelThresholds.length - 1; i >= 0; i--) {
      if (points >= levelThresholds[i]) {
        currentLevel = i;
        break;
      }
    }
    
    // 计算到下一级所需积分
    int nextLevelPoints = currentLevel < levelThresholds.length - 1 
        ? levelThresholds[currentLevel + 1] 
        : levelThresholds.last;
    int currentLevelPoints = levelThresholds[currentLevel];
    int neededPoints = nextLevelPoints - points;
    double progress = currentLevel < levelThresholds.length - 1
        ? (points - currentLevelPoints) / (nextLevelPoints - currentLevelPoints)
        : 1.0;
    
    return {
      'currentLevel': currentLevel,
      'nextLevelPoints': nextLevelPoints,
      'neededPoints': neededPoints > 0 ? neededPoints : 0,
      'progress': progress.clamp(0.0, 1.0),
      'isMaxLevel': currentLevel >= levelThresholds.length - 1,
    };
  }

  /// 获取积分套餐列表
  Future<void> loadPointsPackages() async {
    if (isLoadingPackages.value) return;
    
    try {
      isLoadingPackages.value = true;
      developer.log('🔄 开始加载积分套餐列表');

      final response = await PointsApi.getPointsPackages();
      
      if (response.isSuccess) {
        pointsPackages.clear();
        pointsPackages.addAll(response.sortedPackages);
        
        developer.log('✅ 积分套餐加载成功: ${pointsPackages.length}个套餐');
        
        // 强制UI更新
        update(["funds"]);
      } else {
        developer.log('❌ 积分套餐加载失败: ${response.errorMessage}');
        ToastUtil.error('加载积分套餐失败: ${response.errorMessage}');
      }
    } catch (e) {
      developer.log('💥 加载积分套餐异常: $e');
      ToastUtil.error('加载积分套餐异常');
    } finally {
      isLoadingPackages.value = false;
    }
  }

  /// 刷新用户积分信息
  Future<void> refreshUserPoints() async {
    if (!isLoggedIn) {
      developer.log('⚠️ 用户未登录，无法刷新积分信息');
      return;
    }

    if (isLoadingUserPoints.value) return;
    
    try {
      isLoadingUserPoints.value = true;
      developer.log('🔄 开始刷新用户积分信息');

      final success = await userService.refreshUserInfo();
      
      if (success) {
        developer.log('✅ 用户积分信息刷新成功: ${userPoints}积分');
        update(["funds"]); // 通知UI更新
      } else {
        developer.log('❌ 用户积分信息刷新失败');
        ToastUtil.error('刷新用户信息失败');
      }
    } catch (e) {
      developer.log('💥 刷新用户积分异常: $e');
      ToastUtil.error('刷新用户信息异常');
    } finally {
      isLoadingUserPoints.value = false;
    }
  }

  /// 选择积分套餐
  void selectPackage(int index) {
    if (index >= 0 && index < pointsPackages.length) {
      selectedPackageIndex.value = index;
      developer.log('已选择积分套餐: ${pointsPackages[index].packageName}');
      
      // 强制UI更新以反映选择状态
      update(["funds"]);
    }
  }

  /// 购买积分套餐
  Future<void> purchasePackage() async {
    if (!isLoggedIn) {
      ToastUtil.warning('请先登录');
      return;
    }

    if (selectedPackageIndex.value < 0 || selectedPackageIndex.value >= pointsPackages.length) {
      ToastUtil.warning('请选择要购买的积分套餐');
      return;
    }

    final selectedPackage = pointsPackages[selectedPackageIndex.value];
    
    try {
      developer.log('🔄 开始购买积分套餐: ${selectedPackage.packageName}');
      
      // 检查是否安装了支付宝
      final isAlipayInstalled = await AlipayService.to.isInstalled();
      if (!isAlipayInstalled) {
        ToastUtil.warning('请先安装支付宝客户端');
        return;
      }
      
      ToastUtil.info('正在创建支付订单...');
      
      final response = await PointsApi.createAlipayOrder(
        userId: userService.currentUser!.userid,
        packageId: selectedPackage.packageId,
      );
      
      if (response['status'] == 'success') {
        developer.log('✅ 支付订单创建成功');
        
        // 获取支付宝订单字符串
        final orderString = response['alipay_order_string'];
        
        if (orderString != null && orderString.isNotEmpty) {
          // 调起支付宝支付
          if (AlipayService.to.isIOSSimulator) {
            ToastUtil.info('iOS模拟器环境，将显示模拟支付对话框...');
          } else {
            ToastUtil.info('正在跳转至支付宝...');
          }
          
          final payResult = await AlipayService.to.pay(orderString);
          
          if (payResult != null) {
            await _handlePaymentResult(payResult, selectedPackage);
          } else {
            ToastUtil.error('支付失败，请重试');
          }
        } else {
          ToastUtil.error('支付订单信息异常');
        }
      } else {
        developer.log('❌ 支付订单创建失败: ${response['message']}');
        ToastUtil.error('创建支付订单失败: ${response['message']}');
      }
    } catch (e) {
      developer.log('💥 购买积分套餐异常: $e');
      ToastUtil.error('购买失败，请稍后再试');
    }
  }

  /// 获取积分变更历史
  Future<void> loadPointsHistory() async {
    if (!isLoggedIn) {
      developer.log('⚠️ 用户未登录，无法加载积分变更历史');
      return;
    }
    
    if (isLoadingPointsHistory.value) return;
    
    try {
      isLoadingPointsHistory.value = true;
      developer.log('🔄 开始加载积分变更历史');

      final response = await PointsApi.getPointsHistory(
        userId: userService.currentUser!.userid,
        page: 1,
        pageSize: 20, // 获取最近20条记录
      );
      
      final historyResponse = PointsHistoryResponse.fromJson(response);
      
      if (historyResponse.isSuccess) {
        pointsHistory.clear();
        // 显示所有有效的积分变更记录
        final validRecords = historyResponse.records
            .where((record) => record.status == '有效')
            .toList();
        pointsHistory.addAll(validRecords);
        
        developer.log('✅ 积分变更历史加载成功: ${validRecords.length}条记录');
        
        // 强制UI更新
        update(["funds"]);
      } else {
        developer.log('❌ 积分变更历史加载失败: ${historyResponse.errorMessage}');
        ToastUtil.error('加载积分变更历史失败: ${historyResponse.errorMessage}');
      }
    } catch (e) {
      developer.log('💥 加载积分变更历史异常: $e');
      ToastUtil.error('加载积分变更历史异常');
    } finally {
      isLoadingPointsHistory.value = false;
    }
  }

  /// 初始化数据
  _initData() async {
    developer.log('📱 FundsController 初始化');
    
    // 并行加载积分套餐、刷新用户信息和积分变更历史
    await Future.wait([
      loadPointsPackages(),
      refreshUserPoints(),
      loadPointsHistory(),
    ]);
    
    update(["funds"]);
  }

  void onTap() {}

  /// 处理支付结果
  Future<void> _handlePaymentResult(Map<String, dynamic> result, PointsPackage package) async {
    final resultStatus = result['resultStatus'];
    switch (resultStatus) {
      case '9000':
        // 支付成功
        ToastUtil.success('支付成功！积分将在稍后到账');
        // 刷新用户积分和积分变更历史
        await Future.wait([
          refreshUserPoints(),
          loadPointsHistory(),
        ]);
        // 重置选择
        selectedPackageIndex.value = -1;
        update(["funds"]);
        break;
        
      case '8000':
        // 支付正在处理中
        ToastUtil.info('支付正在处理中，请稍候查看积分变化');
        await refreshUserPoints();
        break;
        
      case '4000':
        // 订单支付失败
        ToastUtil.error('支付失败，请重试');
        break;
        
      case '5000':
        // 重复请求
        ToastUtil.warning('请不要重复支付');
        break;
        
      case '6001':
        // 用户中途取消
        ToastUtil.info('支付已取消');
        break;
        
      case '6002':
        // 网络连接出错
        ToastUtil.error('网络连接异常，请检查网络后重试');
        break;
        
      default:
        ToastUtil.error('支付异常，请联系客服');
        developer.log('未知支付状态: $resultStatus');
    }
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }
}
